﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using DevExpress.XtraTabbedMdi;
using RedRiver.Framework.XtraCommon.FormHelper;
using RedRiver.Framework.XtraCommon.Models;

namespace RedRiver.Framework.XtraCommon.Templates{
    public class MainFrameBase : XtraForm{
        private XtraMdiTabPage _addedPage;

        private BarMdiChildrenListItem _itemMdiChildrenList;
        private BarToolbarsListItem _itemToolbarsList;

        private DockVisibility _navigationPaneVisibility = DockVisibility.Visible;
        private BarSubItem _subItemLookAndFeel;

        protected NavBarControl NavBarControl;

        public MainFrameBase(){
            InitializeComponent();
            ApplyMenuInfo();
        }

        /// <summary>
        /// 主菜单栏
        /// </summary>
        public Bar MainMenuBar{
            get { return _mainMenuBar; }
        }
        /// <summary>
        /// 工具栏
        /// </summary>
        public Bar ToolBar{
            get { return _toolBar; }
        }
        /// <summary>
        /// 状态栏
        /// </summary>
        public Bar StatusBar{
            get { return _statusBar; }
        }

        /// <summary>
        /// 数据导航工具栏
        /// </summary>
        public Bar NavigatorBar{
            get { return _navigatorBar; }
        }

        #region MdiForm

        protected static Form FindMdiChild(Form mdiParent, Type formType, string title){
            foreach (Form item in mdiParent.MdiChildren){
                if ((formType.IsInstanceOfType(item)) &&
                    (item.Text.Equals(title))){
                    item.Activate();
                    return item;
                }
            }
            return null;
        }

        protected static void ShowMdiForm(Form mdiParent, Type formType, string title){
            Form form = FindMdiChild(mdiParent, formType, title);
            if (null != form){
                form.Activate();
                form.Show();
            } else{
                try{
                    XtraMessageForm.ShowMessage("正在打开窗口 [" + title + "] ");
                    var mdiForm = (Form) Activator.CreateInstance(formType, true);
                    mdiForm.MdiParent = mdiParent;
                    mdiForm.Text = title;
                    mdiForm.WindowState = FormWindowState.Maximized;
                    mdiForm.Show();
                    XtraMessageForm.Hiden();
                } catch (Exception ex){
                    Trace.WriteLine(ex.ToString());
                    XtraMessageForm.ShowException("打开窗口失败", ex);
                }
            }
        }

        protected static Form GetMdiForm(Form mdiParent, Type formType, string formTitle){
            foreach (Form item in mdiParent.MdiChildren){
                if ((formType.IsInstanceOfType(item)) &&
                    (item.Text.Equals(formTitle))){
                    item.Activate();
                    return item;
                }
            }
            try{
                var mdiForm = (Form) Activator.CreateInstance(formType, true);
                mdiForm.MdiParent = mdiParent;
                mdiForm.Text = formTitle;
                mdiForm.WindowState = FormWindowState.Maximized;
                return mdiForm;
            } catch (Exception ex){
                Trace.WriteLine(ex.ToString());
                throw new Exception(string.Concat("新建窗口失败,", ex.Message), ex);
            }
        }

        #endregion MdiForm

        /// <summary>
        /// 初始化样式菜单明细
        /// </summary>
        private void InitLookAndFeelListItem(){
            BarItem item = new BarLookAndFeelListItem(defaultLookAndFeel.LookAndFeel);
            mainBarManager.Items.Add(item);
            _subItemLookAndFeel.AddItem(item);
        }

        /// <summary>
        /// 应用预定义的菜单参数
        /// </summary>
        private void ApplyMenuInfo(){
            ApplyMenuInfo(barSubItemFile, FormConst.MenuFileInfo);
            ApplyMenuInfo(barSubItemEdit, FormConst.MenuEditInfo);
            ApplyMenuInfo(barSubItemTools, FormConst.MenuToolsInfo);
            ApplyMenuInfo(barSubItemView, FormConst.MenuViewInfo);
        }

        private static void ApplyMenuInfo(BarItem bItem, MenuItemInfo menuInfo){
            bItem.MergeOrder = menuInfo.MergeOrder;
            //bItem.MergeType = (BarMenuMerge) menuInfo.MergeType;
        }

        private void DockPanelNavigationClosingPanel(object sender, DockPanelCancelEventArgs e){
            barCheckItemNavigationPanelVisibility.Down = false;
        }

        private void BarCheckItemNavigationPaneVisibilityCheckedChanged(object sender, ItemClickEventArgs e){
            if (barCheckItemNavigationPanelVisibility.Down){
                dockPanelNavigation.Visibility = _navigationPaneVisibility;
            } else{
                _navigationPaneVisibility = dockPanelNavigation.Visibility;
                dockPanelNavigation.Visibility = DockVisibility.Hidden;
            }
        }

        protected override void OnHandleCreated(EventArgs e){
            base.OnHandleCreated(e);
            Cursor = Cursors.WaitCursor;
            if (!DesignMode){
                //Text = Application.ProductName + " Ver:" + Application.ProductVersion;
                Icon = NativeMethods.GetAppIcon();
                InitToolBar();
                InitLookAndFeelListItem();
                InitStatusBar();
                InitNavBar();
            }
            Cursor = Cursors.Default;
        }

        protected override void OnClosed(EventArgs e){
            base.OnClosed(e);
            foreach (Form form in MdiChildren){
                form.Close();
            }
            //SaveNavControlLayout();
            Application.Exit();
        }

        /// <summary>
        /// 初始化工具条
        /// </summary>
        protected virtual void InitToolBar(){
            mainBarManager.Images = CommonActionImages.ImageList;
            cExit.ImageIndex = CommonActionImages.IndexActionExit;
            cBuildNavBar.ImageIndex = CommonActionImages.IndexActionOpenObject;
            cBuildNavBar.ItemClick += CBuildNavBarItemClick;
        }

        private void CBuildNavBarItemClick(object sender, ItemClickEventArgs e){
            var builder = new NavBarInfoBuilder();
            builder.NavBarInfo = _navBarInfo;
            builder.ShowDialog(this);
            if (builder.IsDataChanged){
                InitNavBarItems(builder.NavBarInfo);
            }
        }

        /// <summary>
        /// 初始化导航栏
        /// </summary>
        protected virtual void InitNavBar() {}

        /// <summary>
        /// 初始化状态栏
        /// </summary>
        protected virtual void InitStatusBar() {}

        private void CExitItemClick(object sender, ItemClickEventArgs e){
            Close();
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing){
            if (disposing && (components != null)){
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void XtraTabbedMdiManagerPageAdded(object sender, MdiTabPageEventArgs e){
            Form mdiChild = e.Page.MdiChild;
            if (mdiChild.Menu != null){
                var mdibar = new BarManager();
                mdibar.BeginInit();
                var toolbar = new Bar(mdibar, MainMenuBar.BarName){DockStyle = BarDockStyle.Top};
                mdibar.Bars.Add(toolbar);
                foreach (MenuItem mitem in mdiChild.Menu.MenuItems){
                    toolbar.ItemLinks.Add(ConvertToBarItem(mitem, mdibar));
                }
                mdibar.Form = mdiChild;
                mdibar.EndInit();
            }
            //e.Page.Image = ConvertToBitMap(mdiChild.Icon, new Size(16, 16));
            _addedPage = e.Page;
            e.Page.MdiChild.Load += MdiChildLoad;
        }

        private void MdiChildLoad(object sender, EventArgs e){
            try{
                var mdiChild = (Form) sender;
                _addedPage.Image = ConvertToBitMap(mdiChild.Icon, new Size(16, 16));
            } catch (Exception ex){
                Trace.WriteLine(ex.ToString());
            }
        }

        private BarItem ConvertToBarItem(MenuItem menu, BarManager manager){
            BarItem barItem;
            if (menu.MenuItems.Count > 0){
                barItem = new BarSubItem(mainBarManager, menu.Text);
                bool beginGroup = false;
                foreach (MenuItem item in menu.MenuItems){
                    if (item.Text.Equals("-")){
                        beginGroup = true;
                    } else{
                        ((BarSubItem) barItem).ItemLinks.Add(ConvertToBarItem(item, manager), beginGroup);
                        beginGroup = false;
                    }
                }
            } else{
                barItem = new BarButtonItem(mainBarManager, menu.Text);
            }
            barItem.MergeOrder = menu.MergeOrder;
            barItem.Manager = manager;
            barItem.ItemClick += BarItemItemClick;
            barItem.Tag = menu;
            return barItem;
        }

        private static void BarItemItemClick(object sender, ItemClickEventArgs e){
            if (e.Item.Tag is MenuItem){
                ((MenuItem) e.Item.Tag).PerformClick();
            }
        }

        private static Bitmap ConvertToBitMap(Icon icon, Size size){
            Bitmap image;
            if (icon.Size.Equals(size)){
                image = icon.ToBitmap();
            } else{
                image = new Bitmap(size.Width, size.Height);
                Graphics graphics = Graphics.FromImage(image);
                graphics.DrawIcon(icon, new Rectangle(0, 0, size.Width, size.Height));
                graphics.Dispose();
            }
            //Color transparentColor = Color.Transparent; Color.FromArgb(13, 11, 12);
            image.MakeTransparent(Color.White);
            return image;
        }

        private void MainBarManagerMerge(object sender, BarManagerMergeEventArgs e){
            foreach (Bar barItem in mainBarManager.Bars){
                string barName = barItem.BarName;
                if (e.ChildManager.Bars[barName] != null){
                    mainBarManager.Bars[barName].Merge(e.ChildManager.Bars[barName]);
                    e.ChildManager.Bars[barName].Visible = false;
                }
            }
        }

        private void MainBarManagerUnMerge(object sender, BarManagerMergeEventArgs e){
            foreach (Bar barItem in e.ChildManager.Bars){
                string barName = barItem.BarName;
                if (e.ChildManager.Bars[barName] != null){
                    e.ChildManager.Bars[barName].Visible = true;
                }
            }
        }

        private void BarCheckItemNavBarCheckedChanged(object sender, ItemClickEventArgs e){
            dockPanelNavigation.Visibility = barCheckItem_Navigation.Checked
                                                 ? DockVisibility.Visible
                                                 : DockVisibility.AutoHide;
        }

        #region Windows Form Designer generated code

        private DevExpress.XtraBars.Bar _mainMenuBar;
        private DevExpress.XtraBars.Bar _navigatorBar;
        private DevExpress.XtraBars.Bar _statusBar;
        private DevExpress.XtraBars.Bar _toolBar;
        protected BarCheckItem barCheckItem_Navigation;
        protected BarCheckItem barCheckItemNavigationPanelVisibility;
        protected DevExpress.XtraBars.BarDockControl barDockControlBottom;
        protected DevExpress.XtraBars.BarDockControl barDockControlLeft;
        protected DevExpress.XtraBars.BarDockControl barDockControlRight;
        protected DevExpress.XtraBars.BarDockControl barDockControlTop;
        protected BarSubItem barSubItemEdit;
        protected BarSubItem barSubItemFile;
        protected BarSubItem barSubItemHelp;
        protected BarSubItem barSubItemTools;
        protected BarSubItem barSubItemView;
        protected BarButtonItem cBuildNavBar;
        protected DevExpress.XtraBars.BarButtonItem cExit;
        protected DevExpress.XtraBars.BarButtonItem cFilters;
        protected DevExpress.XtraBars.BarButtonItem cFiltersSearch;

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private IContainer components;

        protected DevExpress.XtraBars.BarButtonItem cRecordEdit;
        protected DevExpress.XtraBars.BarButtonItem cRecordsNavigation;
        protected DevExpress.XtraBars.BarButtonItem cView;
        protected DevExpress.XtraBars.BarButtonItem cViewsHistoryNavigation;
        protected DefaultLookAndFeel defaultLookAndFeel;
        protected DockPanel dockPanelNavigation;
        protected ControlContainer dockPanelNavigation_Container;
        protected BarAndDockingController mainBarAndDockingController;
        public BarManager mainBarManager;
        protected DockManager mainDockManager;
        protected XtraTabbedMdiManager xtraTabbedMdiManager;

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent(){
            this.components = new System.ComponentModel.Container();
            this.mainBarManager = new DevExpress.XtraBars.BarManager(this.components);
            this._mainMenuBar = new DevExpress.XtraBars.Bar();
            this.barSubItemFile = new DevExpress.XtraBars.BarSubItem();
            this.cExit = new DevExpress.XtraBars.BarButtonItem();
            this.barSubItemTools = new DevExpress.XtraBars.BarSubItem();
            this.cBuildNavBar = new DevExpress.XtraBars.BarButtonItem();
            this.barSubItemView = new DevExpress.XtraBars.BarSubItem();
            this._itemToolbarsList = new DevExpress.XtraBars.BarToolbarsListItem();
            this._itemMdiChildrenList = new DevExpress.XtraBars.BarMdiChildrenListItem();
            this.barCheckItem_Navigation = new DevExpress.XtraBars.BarCheckItem();
            this._subItemLookAndFeel = new DevExpress.XtraBars.BarSubItem();
            this.barSubItemHelp = new DevExpress.XtraBars.BarSubItem();
            this._statusBar = new DevExpress.XtraBars.Bar();
            this._toolBar = new DevExpress.XtraBars.Bar();
            this._navigatorBar = new DevExpress.XtraBars.Bar();
            this.mainBarAndDockingController = new DevExpress.XtraBars.BarAndDockingController(this.components);
            this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
            this.mainDockManager = new DevExpress.XtraBars.Docking.DockManager(this.components);
            this.dockPanelNavigation = new DevExpress.XtraBars.Docking.DockPanel();
            this.dockPanelNavigation_Container = new DevExpress.XtraBars.Docking.ControlContainer();
            this.NavBarControl = new DevExpress.XtraNavBar.NavBarControl();
            this.barSubItemEdit = new DevExpress.XtraBars.BarSubItem();
            this.cRecordEdit = new DevExpress.XtraBars.BarButtonItem();
            this.cRecordsNavigation = new DevExpress.XtraBars.BarButtonItem();
            this.cViewsHistoryNavigation = new DevExpress.XtraBars.BarButtonItem();
            this.cFiltersSearch = new DevExpress.XtraBars.BarButtonItem();
            this.cFilters = new DevExpress.XtraBars.BarButtonItem();
            this.cView = new DevExpress.XtraBars.BarButtonItem();
            this.barCheckItemNavigationPanelVisibility = new DevExpress.XtraBars.BarCheckItem();
            this.defaultLookAndFeel = new DevExpress.LookAndFeel.DefaultLookAndFeel(this.components);
            this.xtraTabbedMdiManager = new DevExpress.XtraTabbedMdi.XtraTabbedMdiManager(this.components);
            ((System.ComponentModel.ISupportInitialize) (this.mainBarManager)).BeginInit();
            ((System.ComponentModel.ISupportInitialize) (this.mainBarAndDockingController)).BeginInit();
            ((System.ComponentModel.ISupportInitialize) (this.mainDockManager)).BeginInit();
            this.dockPanelNavigation.SuspendLayout();
            this.dockPanelNavigation_Container.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize) (this.NavBarControl)).BeginInit();
            ((System.ComponentModel.ISupportInitialize) (this.xtraTabbedMdiManager)).BeginInit();
            this.SuspendLayout();
            // 
            // mainBarManager
            // 
            this.mainBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[]
                                              {this._mainMenuBar, this._statusBar, this._toolBar, this._navigatorBar});
            this.mainBarManager.Controller = this.mainBarAndDockingController;
            this.mainBarManager.DockControls.Add(this.barDockControlTop);
            this.mainBarManager.DockControls.Add(this.barDockControlBottom);
            this.mainBarManager.DockControls.Add(this.barDockControlLeft);
            this.mainBarManager.DockControls.Add(this.barDockControlRight);
            this.mainBarManager.DockManager = this.mainDockManager;
            this.mainBarManager.Form = this;
            this.mainBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[]{
                                                                                    this.barSubItemFile, this.barSubItemEdit, this.barSubItemView,
                                                                                    this.barSubItemTools, this.barSubItemHelp, this.cExit, this.cRecordEdit,
                                                                                    this.cRecordsNavigation, this.cViewsHistoryNavigation,
                                                                                    this.cFiltersSearch, this.cFilters, this.cView,
                                                                                    this.barCheckItemNavigationPanelVisibility, this._itemMdiChildrenList,
                                                                                    this._itemToolbarsList, this._subItemLookAndFeel, this.cBuildNavBar,
                                                                                    this.barCheckItem_Navigation
                                                                                });
            this.mainBarManager.MainMenu = this._mainMenuBar;
            this.mainBarManager.MaxItemId = 41;
            this.mainBarManager.StatusBar = this._statusBar;
            this.mainBarManager.UnMerge +=
                new DevExpress.XtraBars.BarManagerMergeEventHandler(this.MainBarManagerUnMerge);
            this.mainBarManager.Merge += new DevExpress.XtraBars.BarManagerMergeEventHandler(this.MainBarManagerMerge);
            // 
            // _mainMenuBar
            // 
            this._mainMenuBar.BarName = "MainMenu";
            this._mainMenuBar.DockCol = 0;
            this._mainMenuBar.DockRow = 0;
            this._mainMenuBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
            this._mainMenuBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[]{
                                                                                                     new DevExpress.XtraBars.LinkPersistInfo(this.barSubItemFile),
                                                                                                     new DevExpress.XtraBars.LinkPersistInfo(this.barSubItemTools),
                                                                                                     new DevExpress.XtraBars.LinkPersistInfo(this.barSubItemView),
                                                                                                     new DevExpress.XtraBars.LinkPersistInfo(
                                                                                                         this._subItemLookAndFeel),
                                                                                                     new DevExpress.XtraBars.LinkPersistInfo(this.barSubItemHelp)
                                                                                                 });
            this._mainMenuBar.OptionsBar.AllowQuickCustomization = false;
            this._mainMenuBar.OptionsBar.DrawDragBorder = false;
            this._mainMenuBar.OptionsBar.DrawSizeGrip = true;
            this._mainMenuBar.OptionsBar.UseWholeRow = true;
            this._mainMenuBar.Text = "主菜单";
            // 
            // barSubItemFile
            // 
            this.barSubItemFile.Caption = "文件(&F)";
            this.barSubItemFile.Id = 0;
            this.barSubItemFile.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[]
                                                          {new DevExpress.XtraBars.LinkPersistInfo(this.cExit, true)});
            this.barSubItemFile.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems;
            this.barSubItemFile.Name = "barSubItemFile";
            // 
            // cExit
            // 
            this.cExit.Caption = "退出(&X)";
            this.cExit.Id = 8;
            this.cExit.Name = "cExit";
            this.cExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.CExitItemClick);
            // 
            // barSubItemTools
            // 
            this.barSubItemTools.Caption = "工具(&T)";
            this.barSubItemTools.Id = 3;
            this.barSubItemTools.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[]
                                                           {new DevExpress.XtraBars.LinkPersistInfo(this.cBuildNavBar)});
            this.barSubItemTools.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems;
            this.barSubItemTools.Name = "barSubItemTools";
            // 
            // cBuildNavBar
            // 
            this.cBuildNavBar.Caption = "配置导航栏";
            this.cBuildNavBar.Id = 39;
            this.cBuildNavBar.Name = "cBuildNavBar";
            // 
            // barSubItemView
            // 
            this.barSubItemView.Caption = "视图(&V)";
            this.barSubItemView.Id = 2;
            this.barSubItemView.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[]{
                                                                                                       new DevExpress.XtraBars.LinkPersistInfo(
                                                                                                           this._itemToolbarsList, true),
                                                                                                       new DevExpress.XtraBars.LinkPersistInfo(
                                                                                                           this._itemMdiChildrenList, true),
                                                                                                       new DevExpress.XtraBars.LinkPersistInfo(
                                                                                                           this.barCheckItem_Navigation, true)
                                                                                                   });
            this.barSubItemView.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems;
            this.barSubItemView.Name = "barSubItemView";
            // 
            // _itemToolbarsList
            // 
            this._itemToolbarsList.Caption = "工具条列表";
            this._itemToolbarsList.Id = 37;
            this._itemToolbarsList.Name = "_itemToolbarsList";
            // 
            // _itemMdiChildrenList
            // 
            this._itemMdiChildrenList.Caption = "窗口列表";
            this._itemMdiChildrenList.Id = 36;
            this._itemMdiChildrenList.Name = "_itemMdiChildrenList";
            // 
            // barCheckItem_Navigation
            // 
            this.barCheckItem_Navigation.Caption = "导航栏";
            this.barCheckItem_Navigation.Checked = true;
            this.barCheckItem_Navigation.Id = 40;
            this.barCheckItem_Navigation.Name = "barCheckItem_Navigation";
            this.barCheckItem_Navigation.CheckedChanged +=
                new DevExpress.XtraBars.ItemClickEventHandler(this.BarCheckItemNavBarCheckedChanged);
            // 
            // _subItemLookAndFeel
            // 
            this._subItemLookAndFeel.Caption = "窗口外观(&L)";
            this._subItemLookAndFeel.Id = 38;
            this._subItemLookAndFeel.Name = "_subItemLookAndFeel";
            // 
            // barSubItemHelp
            // 
            this.barSubItemHelp.Caption = "帮助(&H)";
            this.barSubItemHelp.Id = 4;
            this.barSubItemHelp.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems;
            this.barSubItemHelp.Name = "barSubItemHelp";
            // 
            // _statusBar
            // 
            this._statusBar.BarName = "StatusBar";
            this._statusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
            this._statusBar.DockCol = 0;
            this._statusBar.DockRow = 0;
            this._statusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
            this._statusBar.OptionsBar.AllowQuickCustomization = false;
            this._statusBar.OptionsBar.DisableClose = true;
            this._statusBar.OptionsBar.DisableCustomization = true;
            this._statusBar.OptionsBar.DrawDragBorder = false;
            this._statusBar.OptionsBar.DrawSizeGrip = true;
            this._statusBar.OptionsBar.UseWholeRow = true;
            this._statusBar.Text = "状态栏";
            // 
            // _toolBar
            // 
            this._toolBar.BarName = "ToolBar";
            this._toolBar.DockCol = 0;
            this._toolBar.DockRow = 1;
            this._toolBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
            this._toolBar.OptionsBar.AllowRename = true;
            this._toolBar.Text = "工具栏";
            // 
            // NavigatorBar
            // 
            this._navigatorBar.BarName = "NavigatorBar";
            this._navigatorBar.DockCol = 1;
            this._navigatorBar.DockRow = 1;
            this._navigatorBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
            this._navigatorBar.Offset = 47;
            this._navigatorBar.Text = "导航栏";
            // 
            // mainBarAndDockingController
            // 
            this.mainBarAndDockingController.PropertiesBar.AllowLinkLighting = false;
            // 
            // mainDockManager
            // 
            this.mainDockManager.Controller = this.mainBarAndDockingController;
            this.mainDockManager.Form = this;
            this.mainDockManager.RootPanels.AddRange(new DevExpress.XtraBars.Docking.DockPanel[]
                                                     {this.dockPanelNavigation});
            this.mainDockManager.TopZIndexControls.AddRange(new string[]{
                                                                            "DevExpress.XtraBars.BarDockControl",
                                                                            "System.Windows.Forms.StatusBar"
                                                                        });
            // 
            // dockPanelNavigation
            // 
            this.dockPanelNavigation.Controls.Add(this.dockPanelNavigation_Container);
            this.dockPanelNavigation.Dock = DevExpress.XtraBars.Docking.DockingStyle.Left;
            this.dockPanelNavigation.FloatSize = new System.Drawing.Size(146, 428);
            this.dockPanelNavigation.ID = new System.Guid("24977e30-0ea6-44aa-8fa4-9abaeb178b5e");
            this.dockPanelNavigation.Location = new System.Drawing.Point(0, 52);
            this.dockPanelNavigation.Name = "dockPanelNavigation";
            this.dockPanelNavigation.Options.AllowDockBottom = false;
            this.dockPanelNavigation.Options.AllowDockTop = false;
            this.dockPanelNavigation.SavedDock = DevExpress.XtraBars.Docking.DockingStyle.Left;
            this.dockPanelNavigation.SavedIndex = 2;
            this.dockPanelNavigation.Size = new System.Drawing.Size(269, 535);
            this.dockPanelNavigation.TabStop = false;
            this.dockPanelNavigation.Text = "导航栏";
            this.dockPanelNavigation.ClosingPanel +=
                new DevExpress.XtraBars.Docking.DockPanelCancelEventHandler(this.DockPanelNavigationClosingPanel);
            // 
            // dockPanelNavigation_Container
            // 
            this.dockPanelNavigation_Container.Controls.Add(this.NavBarControl);
            this.dockPanelNavigation_Container.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dockPanelNavigation_Container.Location = new System.Drawing.Point(3, 25);
            this.dockPanelNavigation_Container.Name = "dockPanelNavigation_Container";
            this.dockPanelNavigation_Container.Size = new System.Drawing.Size(263, 507);
            this.dockPanelNavigation_Container.TabIndex = 0;
            // 
            // NavBarControl
            // 
            this.NavBarControl.ActiveGroup = null;
            this.NavBarControl.ContentButtonHint = null;
            this.NavBarControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.NavBarControl.Location = new System.Drawing.Point(0, 0);
            this.NavBarControl.Name = "NavBarControl";
            this.NavBarControl.OptionsNavPane.ExpandedWidth = 263;
            this.NavBarControl.Size = new System.Drawing.Size(263, 507);
            this.NavBarControl.StoreDefaultPaintStyleName = true;
            this.NavBarControl.TabIndex = 0;
            this.NavBarControl.Text = "NavBarControl";
            // 
            // barSubItemEdit
            // 
            this.barSubItemEdit.Caption = "编辑(&E)";
            this.barSubItemEdit.Id = 1;
            this.barSubItemEdit.MergeOrder = 20;
            this.barSubItemEdit.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems;
            this.barSubItemEdit.Name = "barSubItemEdit";
            // 
            // cRecordEdit
            // 
            this.cRecordEdit.Caption = "编辑记录";
            this.cRecordEdit.Id = 9;
            this.cRecordEdit.Name = "cRecordEdit";
            // 
            // cRecordsNavigation
            // 
            this.cRecordsNavigation.Caption = "记录导航";
            this.cRecordsNavigation.Id = 10;
            this.cRecordsNavigation.Name = "cRecordsNavigation";
            // 
            // cViewsHistoryNavigation
            // 
            this.cViewsHistoryNavigation.Caption = "导航历史";
            this.cViewsHistoryNavigation.Id = 35;
            this.cViewsHistoryNavigation.Name = "cViewsHistoryNavigation";
            // 
            // cFiltersSearch
            // 
            this.cFiltersSearch.Caption = "搜索";
            this.cFiltersSearch.Id = 11;
            this.cFiltersSearch.Name = "cFiltersSearch";
            // 
            // cFilters
            // 
            this.cFilters.Caption = "条件过滤";
            this.cFilters.Id = 26;
            this.cFilters.Name = "cFilters";
            // 
            // cView
            // 
            this.cView.Caption = "视图";
            this.cView.Id = 12;
            this.cView.Name = "cView";
            // 
            // barCheckItemNavigationPanelVisibility
            // 
            this.barCheckItemNavigationPanelVisibility.Caption = "导航(&N)";
            this.barCheckItemNavigationPanelVisibility.Id = 33;
            this.barCheckItemNavigationPanelVisibility.Name = "barCheckItemNavigationPanelVisibility";
            this.barCheckItemNavigationPanelVisibility.CheckedChanged +=
                new DevExpress.XtraBars.ItemClickEventHandler(this.BarCheckItemNavigationPaneVisibilityCheckedChanged);
            // 
            // xtraTabbedMdiManager
            // 
            this.xtraTabbedMdiManager.Controller = this.mainBarAndDockingController;
            this.xtraTabbedMdiManager.HeaderButtons =
                ((DevExpress.XtraTab.TabButtons)
                 (((DevExpress.XtraTab.TabButtons.Next | DevExpress.XtraTab.TabButtons.Close) |
                   DevExpress.XtraTab.TabButtons.Default)));
            this.xtraTabbedMdiManager.MdiParent = this;
            this.xtraTabbedMdiManager.SetNextMdiChildMode = DevExpress.XtraTabbedMdi.SetNextMdiChildMode.TabControl;
            this.xtraTabbedMdiManager.PageAdded +=
                new DevExpress.XtraTabbedMdi.MdiTabPageEventHandler(this.XtraTabbedMdiManagerPageAdded);
            // 
            // MainFrameBase
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
            this.ClientSize = new System.Drawing.Size(924, 610);
            this.Controls.Add(this.dockPanelNavigation);
            this.Controls.Add(this.barDockControlLeft);
            this.Controls.Add(this.barDockControlRight);
            this.Controls.Add(this.barDockControlBottom);
            this.Controls.Add(this.barDockControlTop);
            this.IsMdiContainer = true;
            this.Name = "MainFrameBase";
            this.Text = "MainFrameBase";
            ((System.ComponentModel.ISupportInitialize) (this.mainBarManager)).EndInit();
            ((System.ComponentModel.ISupportInitialize) (this.mainBarAndDockingController)).EndInit();
            ((System.ComponentModel.ISupportInitialize) (this.mainDockManager)).EndInit();
            this.dockPanelNavigation.ResumeLayout(false);
            this.dockPanelNavigation_Container.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize) (this.NavBarControl)).EndInit();
            ((System.ComponentModel.ISupportInitialize) (this.xtraTabbedMdiManager)).EndInit();
            this.ResumeLayout(false);
        }

        #endregion

        #region NavControl Layout

        private const string DefaultLayoutFolderName = "Layouts";
        private NavBarInfo _navBarInfo;

        /// <summary>
        /// 从指定文件加载导航项目
        /// </summary>
        /// <param name="presistFile"></param>
        protected void InitNavBarItems(string presistFile){
            InitNavBarItems(NavBarInfo.LoadFrom(presistFile));
        }

        /// <summary>
        /// 从指定文件加载导航项目
        /// </summary>
        /// <param name="navBarInfo"></param>
        protected void InitNavBarItems(NavBarInfo navBarInfo){
            if (navBarInfo == null){
                throw new ArgumentNullException("navBarInfo");
            }
            _navBarInfo = navBarInfo;
            XtraMessageForm.ShowMessage("开始加载导航项目...");
            try{
                NavBarControl.Items.Clear();
                NavBarControl.Groups.Clear();
                NavElementInfoCollection groupList = navBarInfo.Items;
                NavBarControl.BeginUpdate();
                foreach (NavBarGroupInfo groupInfo in groupList){
                    XtraMessageForm.ShowMessage("加载程序组" + groupInfo.Caption + "...");
                    groupInfo.AddNavElement(NavBarControl);
                }
                NavBarControl.EndUpdate();
                //启动自动启动组程序
                if (navBarInfo.AutoStartGroup != null){
                    XtraMessageForm.ShowMessage("加载启动组...");
                    foreach (NavBarItemInfo item in (ICollection) navBarInfo.AutoStartGroup.Items){
                        item.PerformClick(NavBarControl.Items[0]);
                    }
                }
                RestoreNavControlLayout(navBarInfo.CreateDate);
                XtraMessageForm.Hiden();
            } catch (Exception ex){
                XtraMessageForm.ShowException("加载导航项目发生错误,", ex);
                var builder = new NavBarInfoBuilder{NavBarInfo = navBarInfo};
                builder.ShowDialog(this);
                if (builder.IsDataChanged){
                    InitNavBarItems(builder.NavBarInfo);
                }
            }
        }

        /// <summary>
        /// 恢复默认的导航布局
        /// </summary>
        private void RestoreNavControlLayout(DateTime createDate){
            string fileName = Path.Combine(GetDefaultLayoutPath(), GetControlLayoutFileName(NavBarControl));
            if (File.Exists(fileName) &&
                (File.GetLastWriteTime(fileName) > createDate)){
                NavBarControl.RestoreFromXml(fileName);
            }
        }

        /// <summary>
        /// 保存默认的导航布局
        /// </summary>
        private void SaveNavControlLayout(){
            string defaultPath = GetDefaultLayoutPath();
            if (!Directory.Exists(defaultPath)){
                Directory.CreateDirectory(defaultPath);
            }
            string fileName = Path.Combine(defaultPath, GetControlLayoutFileName(NavBarControl));
            NavBarControl.SaveToXml(fileName);
        }

        /// <summary>
        /// 表格布局默认路径
        /// </summary>
        /// <returns></returns>
        private static string GetDefaultLayoutPath(){
            string path = Path.Combine(Application.UserAppDataPath, DefaultLayoutFolderName);
            if (!Directory.Exists(path)){
                Directory.CreateDirectory(path);
            }
            return path;
        }

        private string GetControlLayoutFileName(Control control){
            Form form = control.FindForm();
            if (form != null){
                return string.Format("{0}_{1}.layout", form.Name, control.Name);
            }
            return string.Format("{0}_{1}.layout", Name, control.Name);
        }

        #endregion NavControl Layout
    }

    internal class NativeMethods{
        public static Icon GetAppIcon(){
            string fileName = Assembly.GetEntryAssembly().Location;
            IntPtr hLibrary = LoadLibrary(fileName);
            if (!hLibrary.Equals(IntPtr.Zero)){
                IntPtr hIcon = LoadIcon(hLibrary, "#32512");
                if (!hIcon.Equals(IntPtr.Zero)){
                    return Icon.FromHandle(hIcon);
                }
            }
            return null; //no icon was retrieved 
        }

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr LoadIcon(IntPtr hInstance, string lpIconName);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr LoadLibrary(string lpFileName);
    }
}